package org.benjamin.lending.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.benjamin.lending.domain.entity.BorrowInfo;
import org.benjamin.lending.domain.entity.BorrowInfo.Status;
import org.benjamin.lending.domain.entity.BorrowInfoLog;
import org.benjamin.lending.domain.form.AuditForm;
import org.benjamin.lending.domain.form.BorrowIndex;
import org.benjamin.lending.repository.BorrowInfoRepository;
import org.benjamin.lending.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class BorrowServiceImpl implements BorrowService{
	
	private Logger logger = LogManager.getLogger();
	
	@Autowired
	private BorrowInfoRepository borrowInfoRepository;

	@Override
	public void createBorrow(BorrowInfo borrowInfo,String username) {
		borrowInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
		borrowInfo.setStatus(Status.TRIAL);
		borrowInfo.setInvestRate(borrowInfo.getInvestRate().divide(new BigDecimal(100)));
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
		borrowInfo.setNo(dateFormat.toString()+RandomStringUtils.randomNumeric(6));
		if(StringUtils.isNotBlank(username)) {
			logger.info("由后台管理员：【{}】进行创建借款标",username);
			borrowInfo.setCreateUsername(username);
		}
		logger.info("创建借款标");
		this.borrowInfoRepository.save(borrowInfo);
	}

	@Override
	public Page<BorrowInfo> findBorrowPage(final BorrowIndex borrowIndex, Pageable pageable) {
		Specification<BorrowInfo> specification = new Specification<BorrowInfo>() {
			
			@Override
			public Predicate toPredicate(Root<BorrowInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				if(borrowIndex != null) {
					if(StringUtils.isNotBlank(borrowIndex.getName())) {
						list.add(cb.like(root.get("name").as(String.class), "%"+borrowIndex.getName()+"%"));
					}
					if(!borrowIndex.getStatus().isEmpty()) {
						//list.add(cb.equal(root, y))
					}
				}
				Predicate[] predicates = new Predicate[list.size()];
				list.toArray(predicates);
				return query.where(predicates).getGroupRestriction();
			}
		};
		return this.borrowInfoRepository.findAll(specification,pageable);
	}
	
	

	@Override
	public BorrowInfo findByBorrowEntity(Integer borrowId) {
		return this.borrowInfoRepository.findOne(borrowId);
	}

	@Override
	public void auitBorrow(AuditForm auditForm) {
		BorrowInfoLog borrowInfoLog = new BorrowInfoLog();
		BorrowInfo borrowInfo = this.borrowInfoRepository.findOne(auditForm.getBorrowId());
		borrowInfoLog.setBorrowInfo(borrowInfo);
		borrowInfoLog.setMessage(auditForm.getMessage());
		if(auditForm.getAudit()) {
			borrowInfo.setStatus(Status.RELEASE);
			this.borrowInfoRepository.save(borrowInfo);
		}
	}

	@Override
	public void deleteEntity(Integer borrowId) {
		BorrowInfo borrowInfo = this.borrowInfoRepository.findOne(borrowId);
		if(borrowInfo.getStatus().equals(Status.TRIAL)) {
			this.borrowInfoRepository.delete(borrowInfo);
			return;
		}
		throw new IllegalArgumentException("借款标状态有误");
	}

}
